<?php
namespace backend\models;

use Yii;
use yii\base\Model;

class UserForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;
    private $_user = false;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username','password'], 'required'],
            ['rememberMe', 'boolean'],
            ['password', 'validatePassword'],
        ];
    }
    
    public function attributeLabels()
    {
        return array(
            'username' => '用户名',
            'password' => '密码'
        );
    }
    
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if(!$user){
                $this->addError($attribute, '该账号不存在');
                return;
            }
            if(!$user->validatePassword($this->password))
                $this->addError($attribute, '密码输入不正确');
         
        }
    }

    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}
